package com.dycong.common.IO.socket.BIO;

import com.dycong.common.IO.socket.ThreadPoolFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * Created by dycong on 2017/3/23.
 */
public class BIOServer {
    private static final Logger log = LoggerFactory.getLogger(BIOServer.class);

    private static Integer PORT = Integer.valueOf(12122);
    //todo 多线程共享一个ServerSocket，并在创建时用来双重校验锁,静态变量线程共享，不修改静态变量不会有线程安全问题，实例变量每个实例都有自己的实例，不同线程使用不同实例对象不会有线程安全问题
    private static ServerSocket serverSocket = null;
    private static final ThreadPoolFactory threadPoolFactory = new ThreadPoolFactory();

    public BIOServer() {
    }

    public BIOServer(Integer integer) {
        PORT = integer;
    }

    public void start() {
        try {
            start(PORT);
        } catch (IOException e) {
            log.info("serverSocket start error" + e);
            System.out.println("serverSocket start error" + e);
        }
    }

    private static void start(Integer port) throws IOException {
        if (null == serverSocket) {
            synchronized (BIOServer.class) {
                if (null == serverSocket) {
                    serverSocket = new ServerSocket(port);
                    log.info("the serverSocket start Monitor: " + port);
                    System.out.println("the serverSocket start Monitor: " + port);
                }
            }
        }
        Socket socket = null;
        while (true) {
            socket = serverSocket.accept();
            if (socket!=null)
            threadPoolFactory.execute(new ServerHandel(socket));
        }
    }
}
